package cn.itsource.service;

import cn.hutool.http.HttpUtil;
import cn.itsource.config.WXChatProperties;
import cn.itsource.onstans.Constants;
import cn.itsource.pojo.dto.RegisterDto;
import cn.itsource.pojo.dto.UserPhoneAccessToken;
import cn.itsource.pojo.dto.UserPhoneDto;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WxChatService {

    private WXChatProperties wxChatProperties;

    public RegisterDto getWxChatOpenid(String code) {

        //拼接请求
        String formatUrl = String.format(Constants.CODE_2_SESSION, wxChatProperties.getAppid(), wxChatProperties.getAppSecret(), code);
        log.info(formatUrl); //打印拼接地址
        //发送请求
        String result = HttpUtil.get(formatUrl);
        //将json转化为对象
        return JSONObject.parseObject(result, RegisterDto.class);

    }

    public String getUserPhone(String phoneCode) {

       //获取 access_token
        String formatted = String.format(Constants.PHONE_ACCESS_TOKEN, wxChatProperties.getAppid(), wxChatProperties.getAppSecret());
        String result = HttpUtil.get(formatted);
        UserPhoneAccessToken userPhoneAccessToken = JSONObject.parseObject(result, UserPhoneAccessToken.class);
        String accessToken = userPhoneAccessToken.getAccess_token();
        //获取手机号
        String sendUserPhone = String.format(Constants.USER_PHONEN, accessToken);
        HashMap<String, Object> stringHashMap = new HashMap<>();
        stringHashMap.put("code",phoneCode);
        String userPhone = HttpUtil.post(sendUserPhone,stringHashMap);
        //方式一
        /*UserPhoneDto userPhoneDto = JSONObject.parseObject(userPhone, UserPhoneDto.class);
        return userPhoneDto.getPhone_info().getPhoneNumber();*/
        //方式二
        JSONObject jsonObject = JSONObject.parseObject(userPhone);
        JSONObject phoneInfo = (JSONObject) jsonObject.get("phone_info");
        Object phoneNumber = phoneInfo.get("phoneNumber");
        return phoneNumber.toString();
    }
}